package com.kuaishou.locallife.open.api.common.utils;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;

/**
 * web相关工具类
 * PS: 主要包含一些url参数拼接等工具
 *
 * @author shuxiaohui <shuxiaohui@kuaishou.com>
 * Created on 2020-03-31
 */
public class WebUtils {

    public static URL buildGetUrl(String url, String query) throws IOException {
        return KsStringUtils.isEmpty(query)
                ? new URL(url)
                : new URL(buildRequestUrl(url, query));
    }

    public static String buildQueryParams(Map<String, String> params, String charset) throws IOException {
        if (params == null || params.isEmpty()) {
            return null;
        }

        StringBuilder queryParams = new StringBuilder();
        Set<Map.Entry<String, String>> entrySet = params.entrySet();
        boolean hasParam = false;

        for (Map.Entry<String, String> entry : entrySet) {
            String name = entry.getKey();
            String value = entry.getValue();

            if (!KsStringUtils.isBlank(name) && !KsStringUtils.isBlank(value)) {
                if (hasParam) {
                    queryParams.append("&");
                } else {
                    hasParam = true;
                }

                queryParams.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
        }

        return queryParams.toString();
    }

    public static String buildRequestUrl(String url, String... requestParams) {
        if (requestParams == null || requestParams.length == 0) {
            return url;
        }

        StringBuilder requestUrl = new StringBuilder(url);
        boolean hasQuery = url.contains("?");
        boolean hasPrepend = url.endsWith("?") || url.endsWith("&");

        for (String indexQuery : requestParams) {
            if (KsStringUtils.isBlank(indexQuery)) {
                continue;
            }

            if (!hasPrepend) {
                if (hasQuery) {
                    requestUrl.append("&");
                } else {
                    requestUrl.append("?");
                    hasQuery = true;
                }
            }

            requestUrl.append(indexQuery);
            hasPrepend = false;
        }

        return requestUrl.toString();
    }

    private WebUtils() {
    }
}
